package com.foreveross.bsl.mam.app.web;

import java.util.ResourceBundle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.foreveross.bsl.mam.app.application.ClientWsApplication;
import com.foreveross.bsl.mam.app.application.vo.AppVersionVo;

/**
 * 应用商店平台服务接口
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/mam/apps")
public class AppServiceCountroller {

	private final static String ANDROID = "Android";
	private final static String IPHONE = "iPhone";
	private final static String IPAD = "iPad";
	private final static String OTHER = "其它";
	private Log log = LogFactory.getLog(AppServiceCountroller.class);
	private ResourceBundle rb = ResourceBundle.getBundle("config");
	@Inject
	private ClientWsApplication clientWsApplication;

	/**
	 * 根据浏览器类型下载对应租户的上架应用包
	 * 
	 * @param appName
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/download/{identifier:.+}")
	public void downAppByBrowser(@PathVariable("identifier") String identifier,
			String appKey, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String useragent = checkBrowse(request.getHeader("user-agent"));
		String downloadUrl = null;
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath();
		//新增配置文件，可以支持使用http代理请求后台时候，生成plist文件下载地址
		String plistURL = rb.getString("plistURL");
		if (StringUtils.isNotEmpty(plistURL) && plistURL.startsWith("http")) {
			basePath = plistURL;
		}
		if (useragent.equalsIgnoreCase("android")) {
			useragent = "android";
		} else if (useragent.equalsIgnoreCase("iphone")
				|| useragent.equalsIgnoreCase("ipad")) {
			useragent = "ios";
		}

		AppVersionVo versionVo = clientWsApplication.downAppPlat(identifier,
				appKey, useragent, "");
		if (versionVo != null && StringUtils.isNotEmpty(versionVo.getBundle())) {
			downloadUrl = basePath + "/mam/attachment/download/"
					+ versionVo.getBundle();
			if ("ios".equals(useragent)) {// 组装ios itms下载链接 plist
				downloadUrl = basePath + "/mam/attachment/download/"
						+ versionVo.getPlist();
				String installUrl = "itms-services://?action=download-manifest&url=";
				downloadUrl = installUrl + downloadUrl;
			} else {
				log.info("[downAppByBrowser] " + "identifier:" + identifier
						+ " 该平台暂时没有提供下载：" + useragent);
			}
		}

		if (!StringUtils.isEmpty(downloadUrl)) {
			response.sendRedirect(downloadUrl);
		} else {
			log.info("[downAppByBrowser] " + "bundle is null " + " plat:"
					+ useragent);
			String resultMessage = "提示：找不到对应版本的app!";
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			response.setContentLength(resultMessage.getBytes("utf-8").length);
			response.getOutputStream().write(resultMessage.getBytes("utf-8"));
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
	}

	/**
	 * 根据平台下载对应租户的上架应用包
	 * 
	 * @param appName
	 * @return
	 * @throws IOException
	 * 
	 * 
	 */
	@RequestMapping("/download/{identifier}/{platform}")
	public void downAppByPlatform(
			@PathVariable("identifier") String identifier,
			@PathVariable("platform") String platform,
			@RequestParam("appKey") String appKey, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		this.downPackage(identifier, platform, "", appKey, request, response);
	}

	/**
	 * 根据平台版本下载对应的应用包
	 * 
	 * @param appName
	 * @return
	 * @throws IOException
	 * 
	 * 
	 */
	@RequestMapping("/download/{identifier}/{version}/{platform}")
	public void downPackage(@PathVariable("identifier") String identifier,
			@PathVariable("platform") String platform,
			@PathVariable("version") String version,
			@RequestParam("appKey") String appKey, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String downloadUrl = null;
		String basePath = request.getScheme() + "://" + request.getServerName()
				+ ":" + request.getServerPort() + request.getContextPath();
		//新增配置文件，可以支持使用http代理请求后台时候，生成plist文件下载地址
		String plistURL = rb.getString("plistURL");
		if (StringUtils.isNotEmpty(plistURL) && plistURL.startsWith("http")) {
			basePath = plistURL;
		}
		if (platform.equalsIgnoreCase("android")) {
			AppVersionVo versionVo = clientWsApplication.downAppPlat(
					identifier, appKey, "android", version);
			if (versionVo != null
					&& !StringUtils.isEmpty(versionVo.getBundle())) {
				downloadUrl = basePath + "/mam/attachment/download/"
						+ versionVo.getBundle();
			}
		} else if (platform.equalsIgnoreCase("iphone")
				|| platform.equalsIgnoreCase("ipad")
				|| platform.equalsIgnoreCase("ios")) {
			AppVersionVo versionVo = clientWsApplication.downAppPlat(
					identifier, appKey, "ios", version);
			if (versionVo != null
					&& !StringUtils.isEmpty(versionVo.getBundle())) {
				String useragent = checkBrowse(request.getHeader("user-agent"));// 获取浏览器类型
				if (useragent.equalsIgnoreCase("iphone")
						|| useragent.equalsIgnoreCase("ipad")) {
					downloadUrl = basePath + "/mam/attachment/download/"
							+ versionVo.getPlist();
					String installUrl = "itms-services://?action=download-manifest&url=";
					downloadUrl = installUrl + downloadUrl;
				} else {
					downloadUrl = basePath + "/mam/attachment/download/"
							+ versionVo.getBundle();
				}
			}
		} else {
			log.info("[downAppByBrowser] " + "identifier:" + identifier
					+ " 该平台暂时没有提供下载：" + platform);
		}

		if (!StringUtils.isEmpty(downloadUrl)) {
			response.sendRedirect(downloadUrl);
		} else {
			log.info("[downAppByBrowser] " + "bundle is null " + " plat:"
					+ platform);
			String resultMessage = "提示：找不到对应版本的app!";
			response.setContentType("text/html");
			response.setCharacterEncoding("utf-8");
			response.setContentLength(resultMessage.getBytes("utf-8").length);
			response.getOutputStream().write(resultMessage.getBytes("utf-8"));
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}

	}

	private String checkBrowse(String userAgent) {
		if (regex(ANDROID, userAgent))
			return ANDROID;
		if (regex(IPHONE, userAgent))
			return IPHONE;
		if (regex(IPAD, userAgent))
			return IPAD;
		return OTHER;
	}

	private boolean regex(String regex, String str) {
		Pattern p = Pattern.compile(regex, Pattern.MULTILINE);
		Matcher m = p.matcher(str);
		return m.find();
	}
}
